package com.zyz.config;

/**
 * @Author Serendipity
 * @Date 2022/2/11 17:13
 * @Version 1.0
 */


import com.zyz.domain.User;
import com.zyz.handler.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 定义拦截器
 */
public class LoginIntercepter implements HandlerInterceptor {
    /**
     * 拦截器有三个阶段  进入控制器前 离开控制器后  渲染前
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        判断  不同类型登录状态
        User user = (User) request.getSession().getAttribute("userInfo");
        if (user!=null) {
//            将用户设置到 UserHolder中
            UserHolder.setUser(user);
            return true;
        }
//     如果未登录,禁止通行,返回错误
        String json = "请进行登录在操作";
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(json);
        return false;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}